'use strict';

const Controller = require('egg').Controller;

class UserController extends Controller {
    async login() {
        const { ctx, app } = this;
        let { username, password } = ctx.request.body;
        if ((username === "admin" || username === 'guest') && password === "123456") {
            let user_jwt = { username }
            let token = app.jwt.sign(user_jwt, app.config.jwt.secret);
            ctx.body = {
                code: 0,
                data: { token }
            }
        } else {
            ctx.body = {
                code: 1,
                message: "用户名或密码错误"
            }
        }
    }

    async getUserInfo() {
        const { ctx, app } = this;
        // 获取token
        let token = ctx.request.header.token;
        //校验token
        let decode = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
        console.log('decode', decode);
        if (decode.username === 'admin') {
            ctx.body = {
                code: 0,
                data: {
                    roles: ["admin"],
                    "introduction": "I am a super administrator",
                    "avatar": "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
                    "name": decode.username
                }
            };
        } else {
            ctx.body = {
                code: 0,
                data: {
                    roles: ["guest"],
                    "introduction": "I am a guest",
                    "avatar": "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
                    "name": decode.username
                }
            };
        }
    }

    async getMessage() {
        // 不用再校验是否有登录，修改为使用中间件检查
        this.ctx.body = 'message';
    }

    async logout(){
        const { ctx, app } = this;
        // 获取token
        let token = ctx.request.header.token;
        console.log('token',token);
        await app.redis.sadd('token',token);
        ctx.body = {
            code: 0,
            message: '退出登录'
        }
    }
}

module.exports = UserController;
